import { loginApi, getUserInfoApi } from '@/api/user'
import { setToken as setTokenToCookle, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, value) {
    state.token = value
    // 持久化存储token
    setTokenToCookle(value)
  },
  // 保存用户资料
  setUserInfo(state, value) {
    state.userInfo = value
  },
  // 退出登录 => 清除vuex中token，用户信息，重置路由，清除侧边栏信息以及删除cookle中token
  loginOut(state, value) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // 登录
  async login(context, data) {
    const res = await loginApi(data)
    context.commit('setToken', res.data)
    return res
  },
  // 获取用户资料
  async getUserInfo(context) {
    const { data: res } = await getUserInfoApi()
    context.commit('setUserInfo', res)
    return res
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
